import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler  #特征缩放
# from sklearn.linear_model import LogisticRegression #逻辑回归
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix, classification_report  # 评估预测
import joblib as  jlb # 保存模型
#设置字体为楷体
import matplotlib
matplotlib.rcParams['font.sans-serif'] = ['KaiTi']
from data_format import x_train,y_train,x_cross,y_cross,x_test,y_test
from test_result_show import plot_roc,pie_chart

def logistic_regression_train(x_train,y_train,x_cross,y_cross,x_test,y_test):
    # 特征缩放
    sc = StandardScaler()
    x_train = sc.fit_transform(x_train)
    x_cross = sc.fit_transform(x_cross)
    x_test = sc.fit_transform(x_test)

    # 逻辑回归
    # C是正则化系数
    best_C = 1
    best_accurancy = 0
    c_list = []
    accurancy_list = []
    for c in range(1, 60, 1):
        #使用训练集训练模型
        classfier = LogisticRegression(C=c, penalty='l1', solver='liblinear',max_iter=10000)
        classfier.fit(x_train, y_train)

        # 使用交叉验证集评估预测
        y_pred = classfier.predict(x_cross)
        print(classification_report(y_cross, y_pred))

        count = 0
        y_pred_list = y_pred.tolist()
        y_cross_list = y_cross.tolist()
        for i in range(0, len(y_cross)):
            if y_pred_list[i] == y_cross_list[i]:
                count += 1
        if (1.0 * count / len(y_pred)) > best_accurancy:
            best_accurancy = count / len(y_pred)
            best_C = c

        c_list.append(c)
        accurancy_list.append(count / len(y_pred))

    # 绘制c 和 accurancy 的变化曲线
    # show_change_line(c_list, accurancy_list)

    print('best_C:{}'.format(best_C))
    print('best_accurancy:{}'.format(best_accurancy))

    # 将最佳模型保存
    classfier = LogisticRegression(C=best_C, penalty='l1', solver='liblinear')
    classfier.fit(x_train, y_train)
    jlb.dump(classfier, './models/logistic_regression.pkl')

    return c_list, accurancy_list


# 绘制c 和 accurancy 的变化曲线
def show_change_logistic_regression(x, y):
    plt.plot(x, y, c='g', label='accurancy')
    plt.xlabel('C')
    plt.ylabel('accurancy')
    plt.title('正则化参数与准确率的关系')
    plt.legend()
    plt.show()


def LR_result(x_test,y_test):
    # 加载模型
    classfier = jlb.load('./models/logistic_regression.pkl')

    # 对测试集进行预测
    y_pred = classfier.predict(x_test)

    # 画出饼状图
    pie_chart(y_pred,'逻辑回归预测模型(LR)')

    plot_roc(x_test,y_test,y_pred,classfier,'逻辑回归预测模型(LR)')  # 绘制ROC曲线并求出AUC值 以及 评估预测

    print('y_pred:{}'.format(y_pred))



if __name__ == '__main__':
    # c_list, accurancy_list = logistic_regression_train(x_train,y_train,x_cross,y_cross,x_test,y_test)
    # show_change_logistic_regression(c_list, accurancy_list )

    LR_result(x_test, y_test)














